﻿#include <stdio.h>
#include <stdlib.h>

// rtp库依赖socket,必须再rtp库引入之前添加，否则会出各种错误
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

// rtp库引入
#include "jrtplib3/rtpsession.h"
#include "jrtplib3/rtpudpv4transmitter.h"
#include "jrtplib3/rtpipv4address.h"
#include "jrtplib3/rtpsessionparams.h"
#include "jrtplib3/rtperrors.h"
#include "jrtplib3/rtppacket.h"
//#pragma comment(lib, "jrtplib.lib")

using namespace jrtplib;

#pragma warning(disable:4996)

int main(void)
{
	RTPSession  rtpSession;
	RTPSessionParams rtpSessionParams;
	RTPUDPv4TransmissionParams rtpUdpv4Transmissionparams;

	char ip[16] = "127.0.0.1";
	int port = 0;
	int ret = 0;
	char buf[1024] = { 0x00 };

	// 容易忽略，因为自写代码中没有调用socket，rtp有调用但是没有初始化
	WSADATA dat;
	WSAStartup(MAKEWORD(2, 2), &dat);

	printf("This is recver!!!\n");

	printf("Input local port:");
	scanf("%d", &port);
	printf("recv %s:%d\n", ip, port);

	rtpSessionParams.SetOwnTimestampUnit(1.0 / 1);
	rtpSessionParams.SetUsePollThread(true);
	rtpSessionParams.SetAcceptOwnPackets(true);
	rtpUdpv4Transmissionparams.SetPortbase(port);
	ret = rtpSession.Create(rtpSessionParams, &rtpUdpv4Transmissionparams);
	if (ret < 0)
	{
		printf("Failed to RtpSession::Create, ret=%d\n", ret);
	}

	RTPIPv4Address addr(ntohl(inet_addr(ip)), port);
#if 0
	// 组播
	rtpSession.JoinMulticastGroup(addr);
#else
	// 本机接收，127.0.0.1
	rtpSession.AddDestination(addr);
#endif

	while (true)
	{
		rtpSession.BeginDataAccess();
		if (rtpSession.GotoFirstSourceWithData())
		{
			do {
				RTPPacket* packet;
				while ((packet = rtpSession.GetNextPacket()) != NULL)
				{
					unsigned int recvSize = packet->GetPayloadLength();
					unsigned char* recvData = (unsigned char*)packet->GetPayloadData();
					memcpy(buf, recvData, recvSize);
					buf[recvSize] = '\0';
					printf("recv %d, message: %s\n", recvSize, buf);
					rtpSession.DeletePacket(packet);
				}
			} while (rtpSession.GotoNextSourceWithData());
		}
		rtpSession.EndDataAccess();
		RTPTime::Wait(RTPTime(0, 100));
	}
	return 0;
}